<?php

namespace app\api\controller\v35;

use app\api\controller\v2\Auth;
use app\common\cachemodel\MonthFortune;
use app\common\cachemodel\Recode;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\zl2\Zl2AstrFortuneArticle;
use app\common\cachemodel\zl2\Zl2AstrFortuneContent;
use app\common\cachemodel\zl2\Zl2AstrFortuneText;
use app\common\cachemodel\zl2\Zl2AstrFortuneTextZan;
use app\common\cachemodel\zl2\Zl2SurpriseCouponDiscount;
use app\common\cachemodel\zl2\Zl2UserSurpriseRecord;
use app\common\cachemodel\ZlCouponAttr;
use app\common\lib\Util;
use think\response\Json;

class UserAstroFortuneChange extends Auth
{
    protected $recodeInfo = [];
    protected $unlockMonthData = null;

    /**
     * 获取档案信息
     * @param int $rid
     * @return mixed
     * @throws \Exception
     */
    private function getrecodeInfo(int $rid)
    {
        if (isset($this->recodeInfo[$rid]))
        {
            return $this->recodeInfo[$rid];
        }
        $recodeInfo = (new Recode())->getInfoById($rid);

        $this->recodeInfo[$rid] = $recodeInfo;

        return $recodeInfo;
    }

    /**
     * 解锁 星运变动
     * @return Json
     * @throws \Exception
     */
    public function unlockAstroFortuneChange()
    {
        $type = input('type/d', 0); // 1=>首页｜纯净      2=>进行中
        $date = input('date/s', '');

        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $nowTime0 = strtotime(date('Y-m-d')); // 今天零点时间
        if ($type === 1)
        {
            if (!$date)
            {
                return show(config('code.error'), '请求异常，解锁日期缺失～');
            }
            $time = strtotime($date);
            if ($date !== date('Y-m-d', $time))
            {
                return show(config('code.error'), '请求异常，日期格式错误');
            }
            $t1 = $nowTime0 - 86400;
            $t2 = $nowTime0 + 86400;

            if (!in_array($time, [$nowTime0, $t1, $t2], true))
            {   // 今天 ｜ 明天 内 允许解锁    不在这个时间内
                $fortuneMonthUnlockData = $this->getUnlockMonthData($this->user['rid']);
                $isUnlock = in_array(date('Y-n', $time), $fortuneMonthUnlockData, true);
                if (!$isUnlock)
                {
                    return show(config('code.error'), '当月未解锁，不支持计算个人运势～');
                }
            }
        } else
        {   // 直接解锁今天的 进行中数据
            $time = $nowTime0;
        }

        $recodeInfo = (new Recode())->getInfoById($this->user['rid']);
        $recodeHashKey = Util::getRecodeHashKey($recodeInfo);

        $astrFortuneContentModel = new Zl2AstrFortuneContent();
        $info = $astrFortuneContentModel->getUserAstroFortuneChangeData($this->user['id'], $recodeInfo, $time, $type);

        if ($info)
        {
            if (!$info['recode_is_change'])
            {   // 档案未更新
                switch ($info['status'])
                {
                    case 1:
                        return show(config('code.error'), '已经计算过了～');
                    case 2:
                        // 重新发送 计算队列
                        Util::queuePush('astro_fortune_change_calculate', ['id' => $info['id'], 'recode_info' => $recodeInfo], 0);
                        return show(config('code.error'), '已经开始计算了～');
                    default:
                        return show(config('code.success'), '请求成功');
                }
            }
        }

        $d = [
            'uid' => $this->user['id'],
            'rid' => $this->user['rid'],
            'hash' => $recodeHashKey,
            'data_type' => $type,
            'date' => (int)date('Ymd', $time),
            'status' => 0,
            'create_time' => $this->request->time(),
        ];

        $res = $astrFortuneContentModel->SaveData($d, $recodeInfo);
        if ($res)
        {
            return show(config('code.success'), '请求成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 获取 档案 解锁的月运信息
     * @param int $rid
     * @return array|false[]|mixed|string[]|null
     * @throws \Exception
     */
    private function getUnlockMonthData(int $rid)
    {
        if (is_null($this->unlockMonthData))
        {
            $unlockMonths = (new MonthFortune())->getReocdeFortuneUnlockMonths($rid);
            $time_range = array_map(function ($timeValue)
            {
                return date('Y-n', strtotime($timeValue));
            }, $unlockMonths);

            $this->unlockMonthData = $time_range;

            return $time_range;
        }

        return $this->unlockMonthData;
    }

    /**
     * 获取神秘惊喜
     * @return Json
     * @throws \Exception
     */
    public function getSurpriseData()
    {
        $id = input('id/d', 0);

        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if (Util::commentCheck($this->user['id'], ['id' => $id, 'action' => 'getSurpriseData'], 2))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }

        $userSurpriseRecordModel = new Zl2UserSurpriseRecord();

        $surpriseInfo = $userSurpriseRecordModel->getInfoById($id);

        if (!$surpriseInfo || $surpriseInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($surpriseInfo['status'] === 0)
        {   // 未开启 去开启
            if ($surpriseInfo['start_time'] > $this->request->time())
            {
                return show(config('code.error'), '还未到开启惊喜的时间～');
            }
            $userCid = 0;
            if ($surpriseInfo['type'] === 5)
            {   // 发放优惠券
                $couponDiscountInfo = (new Zl2SurpriseCouponDiscount())->getCouponDiscountData($surpriseInfo['sid']);
                $cid = $couponDiscountInfo['list'][$surpriseInfo['sid_node_id']]['cid'];
                $userCouponModel = new UserCoupon();
                $couponInfo = (new ZlCouponAttr())->getInfoById($cid, ['desc', 'type', 'rand_min', 'rand_max', 'ur_id', 'gids', 'discount']);
                $cData = [
                    'uid' => $this->user['id'],
                    'c_id' => $cid,
                    'ur_id' => $couponInfo['ur_id'],
                    'start_time' => $this->request->time(),
                    'end_time' => strtotime("+7 day"),  // 有效期 7 天
                    'give_time' => $this->request->time(),
                    'status' => 0,
                    'price' => $couponInfo['type'] == 4 ? mt_rand($couponInfo['rand_min'], $couponInfo['rand_max']) : 0,
                    'is_give' => 0,
                    'create_time' => $this->request->time(),
                    'update_time' => 0,
                ];
                $ucId = $userCouponModel->insertGetId($cData);
                $userCid = (int)$ucId;
                $surpriseInfo['user_cid'] = $userCid;
                // 未使用
                $userCouponModel->listDataAdd($this->user['id'], [$userCid => $userCid], 1);
            }
            $userSurpriseRecordModel->updateData($id, ['status' => 1, 'user_cid' => $userCid, 'open_time' => $this->request->time()]);
        }
        $resData = $userSurpriseRecordModel->surpriseItemDataResert($surpriseInfo);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 星运变动 天象词条 同感与无感
     */
    public function astroFortuneChangeZan()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0); // 0=>不同感不无感 1=>同感 2=>无感

        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }
        // 验证是否重复操作
        if (Util::commentCheck($this->user['id'], ['id' => $id, 'type' => $type, 'action' => 'astroFortuneChangeZan']))
        {
            return show(config('code.error'), '别心急，等一等');
        }

        $astrFortuneTextModel = new Zl2AstrFortuneText();

        $astrFortuneTextDetail = $astrFortuneTextModel->getInfoById($id, ['zan1', 'zan2']);

        if (!$astrFortuneTextDetail)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        $astrFortuneArticleZanModel = new Zl2AstrFortuneTextZan();

        $zanData = $astrFortuneArticleZanModel->getZan($this->user['id'], [$id]);

        $oldZan = (int)(empty($zanData) ? 0 : $zanData);
        if ($type === $oldZan)
        {
            return show(config('code.success'), '操作成功', $astrFortuneTextDetail);
        }

        $d = [];
        if ($oldZan === 1)
        {
            $d['zan1'] = $astrFortuneTextDetail['zan1'] - 1;
            $astrFortuneTextDetail['zan1'] = $astrFortuneTextDetail['zan1'] - 1;
        }
        if ($oldZan === 2)
        {
            $d['zan2'] = $astrFortuneTextDetail['zan2'] - 1;
            $astrFortuneTextDetail['zan2'] = $astrFortuneTextDetail['zan2'] - 1;
        }
        if ($type === 1)
        {
            $d['zan1'] = $astrFortuneTextDetail['zan1'] + 1;
            $astrFortuneTextDetail['zan1'] = $astrFortuneTextDetail['zan1'] + 1;
        }
        if ($type === 2)
        {
            $d['zan2'] = $astrFortuneTextDetail['zan2'] + 1;
            $astrFortuneTextDetail['zan2'] = $astrFortuneTextDetail['zan2'] + 1;
        }

        $astrFortuneArticleZanModel->setZan($this->user['id'], $id, $type);

        $astrFortuneTextModel->UpdateData($id, $d);

        return show(config('code.success'), '操作成功', $astrFortuneTextDetail);
    }

    /**
     * 星运变动 详情列表
     * @return Json
     * @throws \Exception
     */
    public function detailList()
    {
        $code = input('id/d', 0);
        $status = input('status/d', 0); // // 1=>好（大笑） 2=>平（微笑） 3=>坏（哭）
        $score = input('score/f', -1);  // 感受度
        $date = input('date/s', '');

        if (!$code)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (!in_array($status, [1, 2, 3], true))
        {   // 默认  平
            $status = 2;
        }
        if ($score <= 0)
        {   // 感受度 小于等于0 不显示感受度
            $score = null;
        }
        if ($score >= 1)
        {
            $score = 0.99;
        }
        if ($date)
        {
            if ($date !== (date("Y-m-d", strtotime($date))))
            {
                return show(config('code.error'), '日期格式异常，请稍后再试～');
            }
            $dateTime = strtotime($date);
        } else
        {   // 当天 日期 时间戳
            $dateTime = strtotime(date('Y-m-d'));
        }
        $uid = $this->user ? $this->user['id'] : 0;
        $rid = $this->user ? $this->user['rid'] : 0;

        $recodeInfo = $rid ? $this->getrecodeInfo($rid) : [];

        $data = (new \app\common\cachemodel\zl2\AstroFortuneChange())->getAstroFortuneChangeUnderwayData($uid, $recodeInfo, $code, $status, $dateTime, $score);

        $astrCommunityArticleModel = new Zl2AstrFortuneArticle();

        $articlePages = $astrCommunityArticleModel->getListPage($code, 'id', []);

        $articlePages['data'] = $astrCommunityArticleModel->astrFortuneArticleDataResert($uid, $articlePages['data']);

        return show(config('code.success'), '请求成功', [
            'list' => $articlePages,
            'content_list' => $data
        ]);
    }
}
